import { Body, Controller, Get, Param, Post, Query, Request, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { MessageService } from './message.service';
import { CreateMessageDto } from './dto/create-message.dto';
import { MessageListQueryDto } from './dto/message-list-query.dto';

@ApiTags('Message')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('messages')
export class MessageController {
  constructor(private readonly messageService: MessageService) {}

  // Send message
  @Post()
  @ApiOperation({ summary: 'Send message' })
  @ApiResponse({ status: 201, description: 'Message sent successfully' })
  @ApiBody({ type: CreateMessageDto })
  async create(@Request() req, @Body() createMessageDto: CreateMessageDto) {
    const userId = req.user.id;
    return this.messageService.create(userId, createMessageDto);
  }

  // Get session message list
  @Get('session/:sessionId')
  @ApiOperation({ summary: 'Get session message list' })
  @ApiParam({ name: 'sessionId', description: 'Session ID' })
  @ApiQuery({ name: 'page', required: false, type: Number, description: 'Page number, default is 1' })
  @ApiQuery({ name: 'pageSize', required: false, type: Number, description: 'Items per page, default is 20' })
  @ApiQuery({ name: 'order', required: false, enum: ['asc', 'desc'], description: 'Sort order, default is asc' })
  async getBySessionId(
    @Request() req,
    @Param('sessionId') sessionId: string,
    @Query() query: MessageListQueryDto,
  ) {
    const userId = req.user.id;
    const { page = 1, pageSize = 20, order = 'asc' } = query;
    return this.messageService.getBySessionId(userId, sessionId, page, pageSize, order);
  }

  // Get latest session messages
  @Get('session/:sessionId/latest')
  @ApiOperation({ summary: 'Get latest session messages' })
  @ApiParam({ name: 'sessionId', description: 'Session ID' })
  @ApiQuery({ name: 'limit', required: false, type: Number, description: 'Number of messages, default is 10' })
  async getLatestMessages(
    @Request() req,
    @Param('sessionId') sessionId: string,
    @Query('limit') limit?: number,
  ) {
    const userId = req.user.id;
    const messageLimit = limit ? Math.min(limit, 50) : 10; // Maximum 50 messages
    return this.messageService.getLatestMessages(userId, sessionId, messageLimit);
  }
}
